﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BTv2.Model
{
    public class ComplexCondition : Condition
    {
        public static string AndOperator = "&&";
        public static string OrOperator = "||";

        private Condition _leftSideCondition;
        private Condition _rightSideCondition;
        private string _operator;

        public Condition LeftSideCondition
        {
            get { return _leftSideCondition; }
            set
            {
                if (_leftSideCondition != value)
                {
                    _leftSideCondition = value;
                    NotifyPropertyChanged();
                }
            }
        }
        public Condition RightSideCondition {

            get { return _rightSideCondition; }
            set
            {
                if (_rightSideCondition != value)
                {
                    _rightSideCondition = value;
                    NotifyPropertyChanged();
                }
            }
        }
        public string Operator{
            get { return _operator; }
            set
            {
                if (_operator != value)
                {
                    _operator = value;
                    NotifyPropertyChanged();
                }
            }
        
        }
        public Condition Backup { get; set; }


        public ComplexCondition()
        {
            XamlName = "ComplexCondition";
        }
        public override string ParseCondition()
        {
            return "(" + LeftSideCondition.ParseCondition() + ") " + Operator + " (" + RightSideCondition.ParseCondition() + ")";
        }

        public async override Task<bool> EvaluateCondition()
        {
           if( Operator == AndOperator){
               return await LeftSideCondition.EvaluateCondition() &&  await RightSideCondition.EvaluateCondition();

           }else if(Operator == OrOperator){
               return await LeftSideCondition.EvaluateCondition() || await RightSideCondition.EvaluateCondition();
           }else{
               return false;
           }
        }

        public override string ParseSQLCondition()
        {
            if(Operator == AndOperator){
           return "("+ LeftSideCondition.ParseSQLCondition()+") AND (" + RightSideCondition.ParseSQLCondition()+")";
            }else if(Operator == OrOperator){
                 return "("+ LeftSideCondition.ParseSQLCondition()+") OR (" + RightSideCondition.ParseSQLCondition()+")";
            }else{
                return "";
            }
        }

        public override Condition Copy()
        {
            return new ComplexCondition() {LeftSideCondition = LeftSideCondition.Copy(), Operator = Operator , RightSideCondition = RightSideCondition.Copy(), Parent = Parent };
        }
    }
}
